package com.travel.carmen;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;


/**
	Saved Notes for the Travel Mobile Application Carmen.
	 The View is the Saved Notes List View (layout as per savednotes.xml) for the application.
	 Provides users with access to notes on their Carmen accounts. These notes do
	 require a registered user and are retrieved through XMLRPC requests to Carmen (Drupal) Website.
   	@author Arturo Aparicio 
   	@author Edwin Boykin 
   	@author Veena Chengalnaidu
   	@author Anton Ganeshalingam
   	@author Lakshmi Mallampati
   	@author Tarun Morton
   	@author Chantha Thoeun
*/
public class SavedNotes extends Activity implements OnItemClickListener 
{
	private ListView savedNotes;
	private String result = "";
	private String username;
	private String password;
	private String categoryQueried;
	private int categoryAlphaIndex;
	private ArrayAdapter saved_notes;
	private ArrayList<String> savedNotesItems;
	private ArrayList<String> savedNotesTranslations;
	private ArrayList<Integer> savedNotesNID;
	private ArrayList<String> savedNotesTitles;
	private ArrayList<String> savedNotesLangSrc;
	private ArrayList<String> savedNotesLangTar;
	
	// ProgressDialog
	private ProgressDialog dialog;
	
	@Override
	/**
	   Called when the activity is first created.
	    The UI activities as per savednotes.xml are inflated.
	    All listeners and adapters are attached and all settings are
	    made to default.
	 */
	public void onCreate(Bundle bundle)
	{
		super.onCreate(bundle);
		setContentView(R.layout.savednotes);
		savedNotes = (ListView) findViewById (R.id.list_of_saved_notes);
		username = getIntent().getStringExtra(getString(R.string.username));
		password = getIntent().getStringExtra(getString(R.string.password));
		categoryQueried = getIntent().getStringExtra(getString(R.string.select_category));
		categoryAlphaIndex = getIntent().getIntExtra(getString(R.string.category_position)
				, Main.INVALID);
		savedNotesItems = new ArrayList<String>();
		savedNotesTranslations = new ArrayList<String>();
		savedNotesNID  = new ArrayList<Integer>();
		savedNotesTitles = new ArrayList<String>();
		savedNotesLangSrc = new ArrayList<String> ();
		savedNotesLangTar = new ArrayList<String> ();
		
		savedNotes.setOnItemClickListener(this);
		
		dialog = new ProgressDialog(this);
		dialog.setMessage("Retrieving notes...");
		dialog.setIndeterminate(true);
		
		dialog.show();
		Thread thread = new Thread() 
		{
			@Override
			public void run() 
			{
				//Used to populate notes
				saved_notes = getSavedNotesAdapter(username, password);
				handler.sendEmptyMessage(Main.EMPTY);
			}
		};
		thread.start();
	}
	
	
	/**
	   Handles thread for populating saved notes retrieved through 
	    an XMLRPC request from the Carmen (Drupal) Website.
	    If no Notes are retrieved, activity prepares for return to caller.
	    If Notes are retrieved, activity populates the Saved Notes List View
	 */
	private Handler handler = new Handler() 
	{
        public void handleMessage(Message msg) 
        {
        	dialog.dismiss();
    		
        	// Empty List
    		if (saved_notes.getCount() == Main.EMPTY)
    			returnToCaller();  
    		else
    			savedNotes.setAdapter(saved_notes);
        }
	};
	
	
	/**
	   Returns an Adapter populated with user Notes matching a queried Category.
	   @param username Carmen username
	   @param password corresponding account password
	   @return Adapter populated with user Notes matching a queried Category
	 */
	private ArrayAdapter getSavedNotesAdapter(String username, String password)
	{
		try 
		{
			SharedPreferences settings = getSharedPreferences(
					getString(R.string.app_name), 0);
			String apiKey = settings.getString("apiKey", "");
			String serviceDomain = settings.getString("serviceDomain", "");
			String serviceURL = settings.getString("serviceURL", "");
			DrupalXmlRpcService carmenService = 
				new DrupalXmlRpcService(serviceDomain, apiKey, serviceURL);
			carmenService.connect();
			carmenService.login(username, password);
			// get note nid's & titles
			HashMap<String, String>[] nids = 
				carmenService.viewsGet("user_quicknotes", "user_quicknotes");
			// retrieve view for note
			HashMap<String, Object>[] contents = 
				carmenService.viewsGetNotes("user_quicknotes", "user_quicknotes");
			
			for (int i = 0; i < contents.length; i++)
			{
				String nid      = nids[i].get(DrupalNode.NID);
				String title    = nids[i].get(DrupalNode.TITLE); 
				
				Object notesObj = contents[i].get(DrupalNode.NOTE);
				Object transObj = contents[i].get(DrupalNode.TRANSLATION);
				Object catObj   = contents[i].get(DrupalNode.CATEGORY);
				Object langSrcObj = contents[i].get(DrupalNode.LANGFROM);
				Object langTarObj = contents[i].get(DrupalNode.LANGTO);
				Object[] noteString = (Object[]) notesObj;
				Object[] transString = (Object[]) transObj;
				Object[] catString  = (Object[]) catObj;
				Object[] langSrcString = (Object[]) langSrcObj;
				Object[] langTarString = (Object[]) langTarObj;
				HashMap<String, String>[] noteHM = new HashMap[noteString.length];
				HashMap<String, String>[] transHM = new HashMap[transString.length];
				HashMap<String, String>[] catHM = new HashMap[catString.length];
				HashMap<String, String>[] langSrcHM = new HashMap[langSrcString.length];
				HashMap<String, String>[] langTarHM = new HashMap[langTarString.length];
				
				for (int j = 0; j < noteHM.length; j++)
				{
					if (noteString[j] instanceof HashMap<?, ?>)
						noteHM[j] = (HashMap<String, String>) noteString[j];
				}
				for (int b = 0; b < transHM.length; b++)
				{
					if (transString[b] instanceof HashMap<?, ?>)
						transHM[b] = (HashMap<String, String>) transString[b];
				}
				for (int m = 0; m < catHM.length; m++)
				{
					if (catString[m] instanceof HashMap<?, ?>)
						catHM[m] = (HashMap<String, String>) catString[m];
				}
				for (int ls = 0; ls < langSrcHM.length; ls++)
				{
					if (langSrcString[ls] instanceof HashMap<?, ?>)
						langSrcHM[ls] = (HashMap<String, String>) langSrcString[ls];
				}
				for (int lt = 0; lt < langTarHM.length; lt++)
				{
					if (langTarString[lt] instanceof HashMap<?, ?>)
						langTarHM[lt] = (HashMap<String, String>) langTarString[lt];
				}
				
				String note = "";
				for (int k = 0; k < noteHM.length; k++)
				{
					note = noteHM[k].get("value");
				}
				String trans = "";
				for (int t = 0; t < transHM.length; t++)
				{
					trans = transHM[t].get("value");
				}
				String category = "";
				for (int n = 0; n < catHM.length; n++)
				{
					category = catHM[n].get("value");
				}
				String langSrc = "";
				for (int fls = 0; fls < langSrcHM.length; fls++)
				{
					langSrc = langSrcHM[fls].get("value");
					
				}
				String langTar = "";
				for (int flt = 0; flt < langTarHM.length; flt++)
				{
					langTar = langTarHM[flt].get("value");
					
				}
				
				if (category != null)
				{
					if (category.equals(categoryQueried))
					{
						savedNotesItems.add(note);
						if (trans != null)
						{
							// unescaped fix on retrieval from website
							String unescaped_html =  new Entities().unescape(trans);
			                String replaced = UnescapeHTML.unescapeHTML(unescaped_html, 0);
							savedNotesTranslations.add(replaced);
						}
						if (trans == null)
							savedNotesTranslations.add(Main.BLANK);
						if (title != null)
							savedNotesTitles.add(title);
						if (title == null)
							savedNotesTitles.add(Main.BLANK);
						if (nid != null)
							savedNotesNID.add(Integer.parseInt(nid));
						if (nid == null)
							savedNotesNID.add(DrupalNode.INVALID_NID);
						if (langSrc == null)
							savedNotesLangSrc.add("English");
						if (langSrc != null)
							savedNotesLangSrc.add(langSrc);
						if (langTar == null)
							savedNotesLangTar.add("Spanish");
						if (langTar != null)
							savedNotesLangTar.add(langTar);
					}
					
				}
			}
			
			carmenService.logout();
			return new ArrayAdapter<String>(this, 
	    			android.R.layout.simple_list_item_1, savedNotesItems);
			
		}
		catch (Exception e)
		{ 
			Log.d("[SavedNotes]", "Populating Saved Notes Failed");
			return new ArrayAdapter<String>(this, 
	    			android.R.layout.simple_list_item_1, savedNotesItems);
		}
	}
	
	
	/**
	   Listener for Note selection. Sends Note information from Carmen 
	    (Drupal) website account to caller.
	   @param arg0 Adapter for this Listener
	   @param arg1 View for this Listener
	   @param arg2 Selected Note Position
	   @param arg3 --
	 */
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
			long arg3) 
	{
		result = savedNotes.getAdapter().getItem(arg2).toString();
		String translation = savedNotesTranslations.get(arg2);
		String title  = savedNotesTitles.get(arg2);
		String lang_src = savedNotesLangSrc.get(arg2);
		String lang_tar = savedNotesLangTar.get(arg2);
		int nid       = savedNotesNID.get(arg2);
		
		Intent resultIntent = new Intent();
		resultIntent.putExtra(getString(R.string.query_saved_note), result);
		resultIntent.putExtra(getString(R.string.trans_to_save_note), translation);
		resultIntent.putExtra(getString(R.string.title), title);
		resultIntent.putExtra(getString(R.string.select_category), categoryQueried);
		resultIntent.putExtra(getString(R.string.category_position), categoryAlphaIndex);
		resultIntent.putExtra(DrupalNode.NID, nid);
		resultIntent.putExtra(DrupalNode.LANGFROM, lang_src);
		resultIntent.putExtra(DrupalNode.LANGTO, lang_tar);
		setResult(Activity.RESULT_OK, resultIntent);
		finish();
	}
	
	
	/**
	   Returns to caller with no Notes. 
	    Category Queried has no Notes for this user.
	 */
	private void returnToCaller()
	{
		Intent emptyIntent = new Intent();
		emptyIntent.putExtra(Main.BLANK, categoryQueried);
		setResult(Main.EMPTY, emptyIntent);
		finish();
	}
}
